﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using METU_CMT.Business;

namespace METU_CMT
{
    public class CommonMethods
    {
        public static int GetIdFromGridViewRow(GridViewRow gridViewRow)
        {
            HiddenField _hfId = (HiddenField)gridViewRow.FindControl("hfId");
            int _id;
            return int.TryParse(_hfId.Value, out _id) == false ? 0 : _id;
        }

        public static FileType GetFileType(string ext)
        {
            switch (ext)
            {
                case ".docx":
                    {
                        return FileType.Word;
                    }
                case ".doc":
                    {
                        return FileType.Word;
                    }
                case ".xlsx":
                    {
                        return FileType.Excel;
                    }
                case ".xls":
                    {
                        return FileType.Excel;
                    }
                case ".rar":
                    {
                        return FileType.Zip;
                    }
                case ".zip":
                    {
                        return FileType.Zip;
                    }
                case ".pdf":
                    {
                        return FileType.Pdf;
                    }
            }
            return FileType.NA;
        }

        public static void DownloadFile(HttpResponse response, string filePath, FileType type)
        {
            // Get the physical Path of the file(test.doc)

            // Create New instance of FileInfo class to get the properties of the file being downloaded
            FileInfo _file = new FileInfo(filePath);

            // Checking if file exists
            if (!_file.Exists) return;
            // Clear the content of the response
            response.ClearContent();

            // LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
            response.AddHeader("Content-Disposition", "attachment; filename=" + _file.Name);

            // Add the file size into the response header
            response.AddHeader("Content-Length", _file.Length.ToString());
            String _typeString = string.Empty;
            switch (type)
            {
                case FileType.Word:
                    _typeString = "msword";
                    break;
                case FileType.Excel:
                    _typeString = "vnd.ms-excel";
                    break;
                case FileType.Pdf:
                    _typeString = "pdf";
                    break;
                case FileType.Zip:
                    _typeString = "x-zip-compressed";
                    break;
            }

            // Set the ContentType
            response.ContentType = "application/" + _typeString; // "/vnd.ms-excel";

            // Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
            response.TransmitFile(_file.FullName);

            // End the response
            response.End();
        }

        /// <summary>
        /// calendar dan alınan date'i veritabanında kullanılabilecke date e çevirir.
        /// </summary>
        /// <param name="date">calendar controlünden alınan string date değeri</param>
        /// <param name="format">alınan stringin formatı (kesin çalışan versiyon "yyyy/MM/dd").</param>
        /// <param name="successfull"></param>
        /// <returns>datetime türünden date.</returns>
        public static DateTime ToDateTime(string date, string format, out bool successfull)
        {
            DateTime _tarih;
            CultureInfo _enUs = new CultureInfo("en-US");
            successfull = true;
            if (DateTime.TryParseExact(date, format, CultureInfo.InvariantCulture,
                                         DateTimeStyles.None, out _tarih) == false)
            {
                successfull = false;
            }
            return _tarih;
        }

        public static string CreateRandomPassword(int passwordLength)
        {
            const string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?_-";
            char[] _chars = new char[passwordLength];
            Random _rd = new Random();

            for (int _i = 0; _i < passwordLength; _i++)
            {
                _chars[_i] = allowedChars[_rd.Next(0, allowedChars.Length)];
            }

            return new string(_chars);
        }

        public static void NotifyNewUser(string username, string password, string email, string role)
        {
            string _body = "You are added as a new user to METU CMT System!<br/><b>User Name: </b>" + username +
                           "<br/><b>Password: </b>" +
                           password + "<br/><b>Role: </b>" + role;
            const string mailSubject = "New user notification!";

            Email _email = new Email(mailSubject, _body, email);
            _email.SendEmail();
        }
    }

    public static class ListControlExtensions
    {
        public static int GetSelectedValue(this ListControl ddl)
        {
            int _id;
            if (int.TryParse(ddl.SelectedItem.Value, out _id) == false)
            {
                //TODO: logging
            }
            return _id;
        }
    }

}